import time
import random
from PIL import Image
import pytesseract
import os
from pathlib import Path
import platform

# Windows系统必须设置（根据实际安装路径）
pytesseract.pytesseract.tesseract_cmd = r'c:\Program Files\Tesseract-OCR\tesseract.exe'
 
# 修正后的配置（使用pathlib处理路径）
tesseract_path = Path(r'C:\Program Files\Tesseract-OCR\tesseract.exe')
tessdata_dir = Path(r'C:\Program Files\Tesseract-OCR\tessdata')

pytesseract.pytesseract.tesseract_cmd = str(tesseract_path)
os.environ['TESSDATA_PREFIX'] = str(tessdata_dir.parent)  # 指向Tesseract安装目录
 
 

# def image_to_text(image_path):
#     # 使用原始字符串处理Windows路径
#     config = r'--tessdata-dir C:\Program Files\Tesseract-OCR\tessdata --psm 6'
#     text = pytesseract.image_to_string(
#         Image.open(image_path),
#         lang='eng',
#         config=config
#     )
#     return text.strip()

# 或者更简单的版本（当环境变量正确时）
def image_to_text(image_path):
    return pytesseract.image_to_string(
        Image.open(image_path),
        lang='eng',
        config='--psm 6'
    ).strip()
 
# 添加异常处理
try:
    dirpath = os.path.join(os.getcwd(), 'app', 'interface_walmart', 'png', '777.png')
    text = image_to_text(dirpath)
    print("识别结果:", text)
except pytesseract.TesseractError as e:
    print(f"OCR错误: {e}")
    print(f"最终使用的tessdata路径: {tessdata_dir}\\chi_sim+eng")
    print("请尝试直接运行命令：")
    print(f'"C:\\Program Files\\Tesseract-OCR\\tesseract.exe" "{dirpath}" stdout -l eng --tessdata-dir "C:\\Program Files\\Tesseract-OCR\\tessdata"')
